/*
 * Copyright 2012 Marsrutai.lt
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package lt.marsrutai.mobile.android.activity;

import lt.marsrutai.mobile.android.R;
import lt.marsrutai.mobile.android.manager.ActivityManager;

import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;

import com.android.vending.billing.IInAppBillingService;
import com.google.analytics.tracking.android.EasyTracker;

public class DonationsActivity extends BaseActivity {
    
    public static final String TAG = "billing";
    public static final int BILLING_REQUEST_CODE = 1001;
    public static final int BILLING_RESPONSE_RESULT_OK = 0;
    
    public static final String PRODUCT_ID_LARGE = "marsrutai_android_donation_large";
    public static final String PRODUCT_ID_MEDIUM = "marsrutai_android_donation_medium";
    public static final String PRODUCT_ID_SMALL = "marsrutai_android_donation_small";

    private ActivityManager manager;        
    
    
    private IInAppBillingService mService;
    ServiceConnection mServiceConn = new ServiceConnection() {
       @Override
       public void onServiceDisconnected(ComponentName name) {
           mService = null;
       }

       @Override
       public void onServiceConnected(ComponentName name, 
          IBinder service) {
           mService = IInAppBillingService.Stub.asInterface(service);
           logDebug("STEP 1: onServiceConnected", "onServiceConnected");
           DonationsActivity.this.initialize();
       }
       
       
    };



    @Override
    public void onCreate(Bundle savedInstanceState) {        
        super.onCreate(savedInstanceState);
        manager = new ActivityManager(this, R.string.no_billing_message);
        setContentView(R.layout.progress_spinner);
        manager.showDownloadLoadingBar();

        Boolean bindResult = bindService(new Intent("com.android.vending.billing.InAppBillingService.BIND"), mServiceConn, Context.BIND_AUTO_CREATE);
        logDebug("STEP 0: bindService", String.format("bindService: %s", bindResult));
        if (!bindResult) {
            manager.runOnUiThread(manager.errorRes);
        }
    }
        
    @Override
    protected void onDestroy() {        
        if (mServiceConn != null) {
            unbindService(mServiceConn);
        }    
        super.onDestroy();
    }
    
    private void initialize() {
        setContentView(R.layout.donations_layout);
        setupButtons();
    }
    
    private void setupButtons() {
        findViewById(R.id.donations_large).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                requestPurchase(PRODUCT_ID_LARGE);                 
            }
        });
        
        findViewById(R.id.donations_medium).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                requestPurchase(PRODUCT_ID_MEDIUM);                               
            }
        });
        
        findViewById(R.id.donations_small).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                requestPurchase(PRODUCT_ID_SMALL);                                
            }
        });
    }
    
    // Workaround to bug where sometimes response codes come as Long instead of Integer
    int getResponseCodeFromBundle(Bundle b) {
        Object o = b.get("RESPONSE_CODE");
        if (o == null) {            
            return BILLING_RESPONSE_RESULT_OK;
        }
        else if (o instanceof Integer) return ((Integer)o).intValue();
        else if (o instanceof Long) return (int)((Long)o).longValue();
        else {            
            throw new RuntimeException("Unexpected type for bundle response code: " + o.getClass().getName());
        }
    }
    
    // Workaround to bug where sometimes response codes come as Long instead of Integer
    int getResponseCodeFromIntent(Intent i) {
        Object o = i.getExtras().get("RESPONSE_CODE");
        if (o == null) {            
            return BILLING_RESPONSE_RESULT_OK;
        }
        else if (o instanceof Integer) return ((Integer)o).intValue();
        else if (o instanceof Long) return (int)((Long)o).longValue();
        else {            
            throw new RuntimeException("Unexpected type for intent response code: " + o.getClass().getName());
        }
    }
    
    private void requestPurchase(String productId) {
        
        logDebug("STEP 2: getBuyIntent start", String.format("getBuyIntent start"));
        
        if (mService != null) {
            try {
                Bundle buyIntentBundle = mService.getBuyIntent(3, getPackageName(), productId, "inapp", null);
                
                int response = getResponseCodeFromBundle(buyIntentBundle);
                logDebug("STEP 2: getBuyIntent end", String.format("getBuyIntent end: %s", response));                                           
                if (response != BILLING_RESPONSE_RESULT_OK) {
                    return;
                }
                
                PendingIntent pendingIntent = buyIntentBundle.getParcelable("BUY_INTENT");
                startIntentSenderForResult(pendingIntent.getIntentSender(),
                        BILLING_REQUEST_CODE, new Intent(), Integer.valueOf(0), Integer.valueOf(0),
                        Integer.valueOf(0));
            }
            catch (SendIntentException e) {
                EasyTracker.getTracker().trackException(e.getMessage(), false);
            }
            catch (RemoteException e) {
                EasyTracker.getTracker().trackException(e.getMessage(), false);
            }
        }                
    }
    
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        
        if (requestCode == BILLING_REQUEST_CODE && data != null) {
                        
            int responseCode = getResponseCodeFromIntent(data);
            String purchaseData = data.getStringExtra("INAPP_PURCHASE_DATA");
            String dataSignature = data.getStringExtra("INAPP_DATA_SIGNATURE");
            
            logDebug("STEP 3: onActivityResult", String.format("onActivityResult: %s", responseCode));            
              
            if (responseCode == BILLING_RESPONSE_RESULT_OK) {
                try {
                    // Try consuming
                    JSONObject jo = new JSONObject(purchaseData);
                    String token = jo.getString("purchaseToken"); 
                    consume(getPackageName(), token);
                }
                catch (Exception e) {     
                    Log.e(TAG, e.getMessage());
                }

                // Notify accepted (whether it gets consumed or not)
                notifyDonationAccepted();
            }
        }
        else {
            logDebug("STEP 3: onActivityResult", String.format("onActivityResult: failed"));
        }
    }
    
    
    private void notifyDonationAccepted() {
        // We've got a successful payment!
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setIcon(R.drawable.ic_cup).setTitle(getString(R.string.donations_accepted_title))
            .setMessage(getString(R.string.donations_accepted_message)).setCancelable(false)
            .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {
                    DonationsActivity.this.finish();
                }
            });
        builder.create().show();
        
    }
    
    void consume(final String packageName, final String token) {        
        // Documentation says to do this async. Catch everything...
        (new Thread(new Runnable() {
            public void run() {
                try {
                    logDebug("STEP 4: consumePurchase start", String.format("consumePurchase start: %s", token));
                    int response = mService.consumePurchase(3, packageName, token);
                    logDebug("STEP 4: consumePurchase end", String.format("consumePurchase end: %s", response));                    
                }
                catch (Exception e) {
                    Log.e(TAG, e.getMessage());                    
                }
            }
        })).start();                    
    }
    
    private void logDebug(String event, String message) {
        Log.d(TAG, message);
        EasyTracker.getTracker().trackEvent(TAG,  event, message, 0L);
    }
    

    
    @Override
    public NavMenuData getNavMenuData() {        
        return new NavMenuData(new String[] { this.getString(R.string.donations_title) } );        
    }


}
